<!-- Author: Edwin -->
<template>
  <div>
    <div class="page_header_nextTiket">
      <div class="pagefont_size">{{"NextTicket Rule Template Management"}}</div>
    </div>
    <div class='show-area'
         v-loading="loading">
      <div class="rule-title"
           style="display:flex;align-items: center;margin-bottom:10px">
        <el-tooltip :open-delay="1000" placement="top">
          <div slot="content">Select ConnectWise / AutoTask Default Rule</div>
          <el-select style="width:244px;margin-right:10px;"
                     filterable
                     @change="init"
                     v-model="nextTicketType"
                     >
            <el-option v-for="(item,index) in ruleTypeList"
                       :key="index"
                       :label="item.name"
                       :value="item.value"
                       >
            </el-option>
          </el-select>
        </el-tooltip>
        <div style="flex-grow: 1;display: flex;justify-content: flex-end;">
          <el-button @click="saveAllRule()" :disabled="!currentTemplateId"
                     size="small"
                     type="primary">Save All</el-button>
        </div>
      </div>
      <div style="margin-bottom: 20px;font-weight: 600;margin-top: 20px;font-size:16px">
        <el-tooltip :open-delay="1000" class="item"
                    effect="dark"
                    content="Click to Collapse All"
                    v-if="expandAllVal"
                    placement="top">
          <el-button @click="onStateChange"
                     class="cuifont icon_chevron_collapse_vertical"
                     style="fontSize:14px;padding:7px;margin-right:10px;"></el-button>
        </el-tooltip>
        <el-tooltip :open-delay="1000" class="item"
                    effect="dark"
                    content="Click to Expand All"
                    v-else
                    placement="top">
          <el-button @click="onStateChange"
                     class="cuifont icon_chevron_expand_vertical"
                     style="fontSize:14px;padding:7px;margin-right:10px;"></el-button>
        </el-tooltip>
        <el-select v-model="currentTemplateId" @change="changeTemplate">
          <el-option
            v-for="item in templateOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
        <el-button style="margin-left:10px" :disabled="!currentTemplateId" size="mini" v-if="$hasPermission('sys:nextticket:saveastemplate')" @click="deleteTempalte" type="primary">{{$t('custom.nextTicket.deletethistemplate')}}</el-button>
        <el-button size="mini" v-if="$hasPermission('sys:nextticket:saveastemplate')" @click="create" type="primary">{{$t('custom.nextTicket.createnewtemplate')}}</el-button>
      </div>
      <el-dialog
          :title="$t('custom.nextTicket.createnewtemplate')"
          :visible.sync="templateVisible"
          width="30%"
          @close="reset">
          <div v-loading="templateLoading">
            <div style="margin-bottom:10px">{{$t('custom.nextTicket.templatename')}}</div><el-input v-model="templateName"></el-input>
            <div slot="footer" class="dialog-footer">
              <el-button size="mini" @click="templateVisible = false">{{$t('cancel')}}</el-button>
              <el-button size="mini" type="primary" :disabled="!templateName" @click="saveAsTemplate">{{$t('save')}}</el-button>
            </div>
          </div>
        </el-dialog>
      <div class="rule-area"
           v-loading='listLoading'>
        <el-collapse v-model="activeRules"
                     @change="handleChange"
                     class="rule-area-list scroll-css"
                     id="scrollBox">
          <el-collapse-item v-for="(item,index) in ruleList"
                            v-loading='saveLoading && tempLoadName === item.name'
                            :key="index"
                            :name="item.name">
            <template slot="title">
              <div class="rule-area-list-title">
                <div class="rule-area-list-title-btn"
                     style="margin-right:10px">
                  <div class="rule-area-list-title-btn-switch"
                       @click.stop>
                    <el-switch v-model="item.enable"
                               @change="enableChangeRule(item,index)"
                               size="mini"
                               type="primary"> Enable</el-switch>
                  </div>
                </div>
                <div class="rule-area-list-title-name">{{ item.displayName }}
                  <el-tooltip :open-delay="1000" :content="item.toolTips"
                              placement="top">
                    <i class="cuifont icon_info_circle_fill"
                       style="color:#303133;vertical-align:top"></i>
                  </el-tooltip>
                </div>
              </div>
            </template>
            <div class="rule-area-list-content"
                 v-show="item.checkbox">
              <div   v-if="!loading">
                <div v-if="item.name!=='STATUS_POINTS_GRADE_RULE'">
                <div :data-computed='item.params.length === 0 ? getParamsList(item) : ""'></div>
                <draggable v-model="item.params">
                  <transition-group>
                    <div v-for="(its,i) in item.params"
                         :key="findIndex(its,i)"
                         class="condition-item">
                      <div class="condition-item-icon"
                           :style="{ width: getTemplate(item.name).template.length === 1 && getTemplate(item.name).template[0].type === 'input' && 0 }">
                        <el-button @click="addConditionItem(i, item)"
                                   type="primary"
                                   plain
                                   size="mini"
                                   icon="el-icon-plus"
                                   circle></el-button>
                        <el-button @click="removeConditionItem(i, item.params)"
                                   :disabled="i === 0 && item.params.length === 1"
                                   type="danger"
                                   plain
                                   size="mini"
                                   icon="el-icon-minus"
                                   circle></el-button>
                      </div>
                      <NextTicketRander :showJson='getTemplate(item.name).template'
                                        :params='its'
                                        :parentIndex='index'
                                        :paramsIndex='i'
                                        ref="NextTicketRander"
                                        class="condition-item-content"
                                        :style="{ width: getTemplate(item.name).template.length === 1 && getTemplate(item.name).template[0].type === 'input' && '100%' }" />
                    </div>
                  </transition-group>
                </draggable>
              </div>
              <div v-else>
                <NextTicketRanderTable :showJson='getTemplate(item.name).template'
                                       :params='item.params'
                                       :autotask="autotask"
                                       class="condition-item-content"
                                       style="width:100%" />
              </div>
              </div>
            </div>
            <div style="display:flex;justify-content:flex-end;padding:0 12px 12px 12px"
                 >
              <div @click.stop>
                <el-button @click="saveRule(item,index)"
                           plain
                           size="mini"
                           type="primary">Save</el-button>
              </div>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>

    </div>
  </div>

</template>

<script>
import NextTicketRander from '@/components/next-ticket-render/index'
import NextTicketRanderTable from '@/components/next-ticket-render/table'

import draggable from 'vuedraggable'

export default {
  props: {
  },
  components: { NextTicketRander, NextTicketRanderTable, draggable },
  data () {
    return {
      scrollTop: 0,
      scrollTopFlag: false,
      activeRules: [],
      activeRulesFlag: true,
      ruleList: [],
      templateList: [],
      saveLoading: false,
      tempLoadName: null,
      listLoading: false,
      loading: false,
      expandAllVal: true,
      ruleTypeList: [],
      nextTicketType: '',
      autoTaskRuleList: [],
      cwRuleList: [],
      templateOptions: [],
      currentTemplateId: null,
      templateVisible: false,
      templateName: '',
      templateLoading: false
    }
  },
  computed: {
  },
  created () {
    try {
      let arr = this.$store.state.nextTicket.nextTicketAppList
      this.ruleTypeList = arr.map(i => {
        return {
          name: i.appParam && i.appParam.nextTicketName,
          value: i.appParam && i.appParam.nextTicketType
        }
      })
      this.nextTicketType = this.ruleTypeList[0].value
    } catch (error) {

    }
    this.getPSA()
    
  },
  mounted () { this.recoredScrollT() },
  methods: {
    reset () {
      this.templateName = ''
      this.templateVisible = false
    },
    create () {
      this.templateVisible = true
    },
    saveAsTemplate () {
      let saveData = this.templateList
      // if (this.nextTicketType.replace('dataset','')  === 'autotask') {
      //   saveData = this.templateList.filter((e) => e.systemName === 0 || e.systemName === 2)
      // } else if (this.nextTicketType.replace('dataset','')  === 'nextTicket') {
      //   saveData = this.templateList.filter((e) => e.systemName === 0 || e.systemName === 1)
      // } else if (this.nextTicketType.replace('dataset','')  === 'syncro') {
      //   saveData = this.templateList.filter((e) => e.systemName === 0 || e.systemName === 3)
      // } else if (this.nextTicketType.replace('dataset','')  === 'kaseyabms') {
      //   saveData = this.templateList.filter((e) => e.systemName === 0 || e.systemName === 4)
      // }
      if (saveData && saveData.length > 0) {
        this.templateLoading = true
        this.updateRuleRequest(saveData, null, this.templateName)
      }
    },
    changeTemplate (id) {
      this.getRuleList(id)
    },
    getRuleList (id) {
      this.listLoading = true
      this.scrollTopFlag = false
      this.ruleList = []
      const params = {
        modelId: id,
        type: this.nextTicketType
      }
      if (this.nextTicketType.replace('dataset','')  === 'autotask') {
        this.$interface.apiManager.getTenantRuleListApi(this.$store.state.user.tenantCode, params)
          .then(({ data: res }) => {
            if (res.code !== 0) {
              return this.$message.error(res.msg)
            }
            this.listLoading = false
            // var data = []
            // res.data.forEach(element => {
            //   if (element.displayName === 'Priority Type' || element.displayName === 'Company Matched to User') {
            //     data.push(element)
            //   }
            // })
            // this.ruleList = data
            // // || element.displayName === 'Company Matched to User'
            this.ruleList = this.filterTemplateListChecke(res.data)
            this.setScrollBoxScrollT()
            if (this.ruleList.length === 0) {
              this.initRuleTemp()
            }
          })
          .catch(() => {
            this.listLoading = false
            this.ruleList = []
          })
      } else {
        this.$interface.nextTicket.getTenantRuleListApi(this.$store.state.user.tenantCode, params)
          .then(({ data: res }) => {
            if (res.code !== 0) {
              return this.$message.error(res.msg)
            }
            this.listLoading = false
            // var data = []
            // res.data.forEach(element => {
            //   if (element.displayName === 'Priority Type' || element.displayName === 'Company Matched to User') {
            //     data.push(element)
            //   }
            // })
            // this.ruleList = data
            // // || element.displayName === 'Company Matched to User'
            this.ruleList = this.filterTemplateListChecke(res.data)
            this.setScrollBoxScrollT()
            if (this.ruleList.length === 0) {
              this.initRuleTemp()
            }
          })
          .catch(() => {
            this.listLoading = false
            this.ruleList = []
          })
      }
    },
    deleteTempalte () {
      this.$confirm(this.$t('custom.nextTicket.deletetemplatetext'), this.$t('custom.nextTicket.deletetemplate'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        // type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        var params = {
          id: this.currentTemplateId,
          type: this.nextTicketType
        }
        this.loading = true
        this.$interface.nextTicket.delNextTicketTemplate(params)
          .then(({ data: res }) => {
            if (res.code !== 0) {
              this.loading = false
              return this.$message.error(res.msg)
            }
            this.$message.success('Success')
            this.getNextTicketTemplateList()
            this.loading = false
          }).catch(() => { this.loading = false })
      })
    },
    getNextTicketTemplateList (currentTemplateId) {
      const params = {
        type: this.nextTicketType
      }
      this.templateOptions = []
      this.$interface.nextTicket.getNextTicketTemplateList(params).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        if (res.data.length > 0) {
          this.templateOptions = res.data
          if (this.templateOptions.length > 0) {
            this.currentTemplateId = currentTemplateId || this.templateOptions[0].id
            this.getRuleList(currentTemplateId || this.currentTemplateId)
          }
        } else if (res.data.length === 0) {
          this.currentTemplateId = ''
          this.getTemplateList()
        }
      }).catch(() => {
      })
    },
    recoredScrollT () {
      this.$nextTick(() => {
        document.getElementById('scrollBox').addEventListener('scroll', (e) => {
          if (this.scrollTopFlag) this.scrollTop = e.target.scrollTop
          this.scrollTopFlag = true
        }, false)
      })
    },
    setScrollBoxScrollT () {
      this.$nextTick(() => { if (this.scrollTop) document.getElementById('scrollBox').scrollTop = this.scrollTop })
    },
    onStateChange () {
      this.expandAllVal = !this.expandAllVal
      if (!(this.ruleList.length > 0)) return
      if (this.expandAllVal) {
        this.ruleList.forEach(element => {
          element.checkbox = true
          this.activeRules.push(element.name)
        })
      } else {
        this.activeRules = []
      }
    },
    // chanegRuleType (val) {
    //   this.currentTemplateId = null
    //   this.ruleList = []
    //   if (val === 'autotask') {
    //     this.$set(this, 'ruleList', this.templateList.filter((e) => e.systemName === 0 || e.systemName === 2))
    //   } else if (val === 'nextTicket') {
    //     this.$set(this, 'ruleList', this.templateList.filter((e) => e.systemName === 0 || e.systemName === 1))
    //   } else if (val === 'syncro') {
    //     this.$set(this, 'ruleList', this.templateList.filter((e) => e.systemName === 0 || e.systemName === 3))
    //   } else if (val === 'kaseyabms') {
    //     this.$set(this, 'ruleList', this.templateList.filter((e) => e.systemName === 0 || e.systemName === 4))
    //   }
    //   this.getNextTicketTemplateList()
    //   this.$forceUpdate()
    // },
    findIndex (item, index) {
      let i = 0
      if (item.index) {
        i = item.index
      } else {
        i = index
      }
      return i
    },
    init () {
      
      this.getTemplateList()
      this.getNextTicketTemplateList()
    },
    getPSA() {
      this.$interface.getStarted.getMspInfoApi()
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
       try {
        
         let value = res.data.tenantSoftwareMap.selectedPSA[0].value
         if(value) {
          if(value.includes('Syncro')) {
            this.nextTicketType = 'syncro'
          }else if(value.includes('Kaseya')) {
            this.nextTicketType = 'kaseyabms'
          }else if(value.includes('ConnectWise')) {
            this.nextTicketType = 'nextTicket'
          }else if(value.includes('AutoTask')) {
            this.nextTicketType = 'autotask'
          }
         }
         this.init()
       } catch (error) {
        
       }
        })
    },
    handleChange (val) {
      this.ruleList.forEach((e, i) => {
        if (val.includes(e.name)) e.checkbox = true
      })
    },
    getTemplateList () {
      let params = {
        type: this.nextTicketType
      }
      this.loading = true
      this.$interface.nextTicket.getRuleTemplateListApi(params)
        .then(({ data: res }) => {
          this.loading = false
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.templateList = res.data
          this.ruleList = this.filterTemplateListChecke(res.data)
        })
        .catch(() => {
          this.loading = false
          this.templateList = []
        })
    },
    filterTemplateListChecke (list) {
      try {
        list.forEach((e, i) => {
          if (this.activeRules.includes(e.name)) e.checkbox = true
          else e.checkbox = false
          let hasItem = this.templateList.find(item => item.name === e.name)
          if (hasItem) e.toolTips = hasItem.toolTips
          if (this.activeRulesFlag) {
            this.activeRules.push(e.name)
            e.checkbox = true
          }
          if (e.name === 'MEMBER_SKILLS_POINT_RULE') {
            e.params.forEach(element => {
              element.onlyId = new Date().getTime()
            })
          }
        })
        this.activeRulesFlag = false
        // if (this.nextTicketType && this.nextTicketType.replace('dataset','')  === 'autotask') {
        //   this.autoTaskRuleList = list.filter((e) => e.systemName === 0 || e.systemName === 2)
        //   return list.filter((e) => e.systemName === 0 || e.systemName === 2)
        // } else if (this.nextTicketType.replace('dataset','')  === 'nextTicket') {
        //   this.cwRuleList = list.filter((e) => e.systemName === 0 || e.systemName === 1)
        //   return list.filter((e) => e.systemName === 0 || e.systemName === 1)
        // } else if (this.nextTicketType.replace('dataset','')  === 'syncro') {
        //   return list.filter((e) => e.systemName === 0 || e.systemName === 3)
        // } else if (this.nextTicketType.replace('dataset','')  === 'kaseyabms') {
        //   return list.filter((e) => e.systemName === 0 || e.systemName === 4)
        // }
        return list
      } catch (error) {
        console.log(error)
      }
    },
    getTemplate (name) {
      try {
        // this.autoTaskRuleList = []
        // this.cwRuleList = []
        // if (this.templateList.find(e => e.name === name && this.nextTicketType && this.nextTicketType.replace('dataset','')  === 'autotask' && (e.systemName === 2 || e.systemName === 0))) {
        //   this.autoTaskRuleList = this.templateList.find(e => e.name === name)
        //   return this.templateList.find(e => e.name === name)
        // } else if (this.templateList.find(e => e.name === name && this.nextTicketType && this.nextTicketType.replace('dataset','')  === 'nextTicket' && (e.systemName === 1 || e.systemName === 0))) {
        //   this.cwRuleList = this.templateList.find(e => e.name === name)
        //   return this.templateList.find(e => e.name === name)
        // } else if (this.templateList.find(e => e.name === name && this.nextTicketType && this.nextTicketType.replace('dataset','')  === 'syncro' && (e.systemName === 3 || e.systemName === 0))) {
        //   return this.templateList.find(e => e.name === name)
        // } else if (this.templateList.find(e => e.name === name && this.nextTicketType && this.nextTicketType.replace('dataset','')  === 'kaseyabms' && (e.systemName === 4 || e.systemName === 0))) {
        //   return this.templateList.find(e => e.name === name)
        // } return { template: [] }
        return this.templateList.find(e => e.name === name)
      } catch (error) {
        return { template: [] }
      }
    },
    addConditionItem (index, item) {
      let tempList = this._.cloneDeep(this.templateList.find(e => e.name === item.name).params, [])
      let lastObj = {}
      for (const key in tempList[0]) {
        lastObj[key] = null
      }
      var indexs = item.params.map(item => {
        return item.index
      })
      lastObj.selected = item.enable
      lastObj.width = ''
      lastObj.onlyId = new Date().getTime()
      lastObj.index = Math.max(...indexs) + 1
      item.params.splice(index + 1, 0, lastObj)
    },
    removeConditionItem (index, arrayOrigin) {
      arrayOrigin.splice(index, 1)
    },
    getParamsList (item) {
      try {
        item.params = this._.cloneDeep(this.templateList.find(e => e.name === item.name).params, [])
      } catch (error) { }
    },
    enableChangeRule (item, i) {
      if (this.validateCheckRule(item, i)) {
        this.saveRule(item, i)
      } else {
        item.enable = false
      }
    },
    validateCheckRule (item, i) {
      let isSubmit = true
      if (this.$refs.NextTicketRander) {
        for (let index = 0; index < this.$refs.NextTicketRander.length; index++) {
          const element = this.$refs.NextTicketRander[index]
          if (element.parentIndex === i) {
            let thisValid = element.validateRules()
            if (!thisValid && item.enable) isSubmit = false
          }
        }
      }
      return isSubmit
    },
    saveRule (item, i) {
      if (this.validateCheckRule(item, i)) {
        if (item && item.params) {
          var itemclone = null
          itemclone = this.filterNullSaveParams(item)
          const params = {
            ...itemclone
          }
          if (itemclone && itemclone.params.length > 0) {
            this.saveLoading = true
            this.tempLoadName = item.name
            this.updateRuleRequest([params], null, null, this.currentTemplateId)
          }
        }
      }
    },
    saveAllRule () {
      this.listLoading = true
      var saveData = []
      let isSubmit = true
      this.ruleList.forEach((element, index) => {
        var itemparms = this.filterNullSaveParams(element)
        if (itemparms && itemparms.params && itemparms.params.length > 0) {
          isSubmit = this.validateCheckRule(itemparms, index)
          saveData.push(itemparms)
        }
      })
      if (isSubmit) {
        this.activeRules = []
        if (saveData && saveData.length > 0) {
          this.updateRuleRequest(saveData, null, null, this.currentTemplateId)
        } else this.listLoading = false
      } else this.listLoading = false
    },
    updateRuleRequest (params, from, templateName, currentTemplateId) {
      this.$interface.nextTicket.updateTenantRuleApi(this.$store.state.user.tenantCode, params, this.nextTicketType, templateName, currentTemplateId)
        .then(({ data: res }) => {
          this.saveLoading = false
          this.tempLoadName = null
          this.listLoading = false
          this.templateLoading = false
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$message.success(res.msg)
          if (from) this.getDataList()
          if (templateName) {
            this.getRuleList(res.data[0].modelId)
            this.getNextTicketTemplateList(res.data[0].modelId)
            this.templateVisible = false
          } else {
            this.getRuleList(currentTemplateId)
          }
        })
        .catch(() => {
          this.saveLoading = false
          this.tempLoadName = null
          this.listLoading = false
          this.templateLoading = false
        })
    },
    filterNullSaveParams (item) {
      if (item.name === 'STATUS_POINTS_GRADE_RULE') {
        return this._.cloneDeep(item, {})
      }
      var removeIndex = []
      var index = 0
      item.params.forEach(element => {
        for (var i in element) {
          if (element[i] === null || element[i] === '' || element[i] === undefined) {
            removeIndex.push(index)
            item.checkbox = true
            this.$set(item, 'checkbox', true)
            break
          }
        }
        index++
      })
      // remove null item
      var itemclone = this._.cloneDeep(item, {})
      return itemclone
    }
  },
  destroyed () {
    if (document.getElementById('scrollBox'))document.getElementById('scrollBox').removeEventListener('scroll', (e) => { }, false)
  }
}
</script>

<style scoped lang='scss'>
@import "./index.scss";
::v-deep i.el-icon-arrow-right {
  display: none;
}
::v-deep .el-dialog {
  display: flex;
  flex-direction: column;
  margin: 0 !important;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  /*height:600px;*/
  max-height: calc(100% - 90px);
  max-width: calc(100% - 30px);
}
::v-deep .el-dialog .el-dialog__body {
  flex: 1;
  overflow: auto;
}
::v-deep .el-input__inner {
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}
.rule-area {
  height: calc(100vh - 310px) !important;
}
.rule-area .scroll-css {
  height: 100%;
}
.show-area {
  height: 100%;
}
</style>
<style lang="scss">
.rule-area-list {
  .el-collapse-item__content {
    padding-bottom: 0;
  }
}
.page_header_nextTiket {
  height: 40px;
  background-color: #fff;
  display: flex;
  justify-content: space-between;
  padding: 0 10px;
  align-items: center;
  .back_icon {
    margin: 0 10px;
    cursor: pointer;
  }
  .back_icon::before {
    font-size: 18px;
  }
  .pagefont_size {
    font-size: 16px;
    font-weight: 600;
    color: rgba(0, 0, 0, 0.75);
  }
}
</style>
